package com.feiyuan.core.filter;

import com.feiyuan.common.utils.ObjectMapperUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @ClassName SrbWebFilter
 * @Description 后台过滤器
 * @Author Xupf xupengfei131276@126.com
 * @Date 2021/9/30 9:45
 * @Version 1.0
 */
@Component
@WebFilter(urlPatterns = {"/*"}, filterName = "srbWebFilter")
@Order(2)
public class SrbWebFilter implements Filter {

    private Logger logger = LoggerFactory.getLogger(SrbWebFilter.class);

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private RequestMappingHandlerMapping requestMappingHandlerMapping;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        logger.info("==============初始化过滤器=================");
        Filter.super.init(filterConfig);
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        String uri = request.getRequestURI();
        logger.info("uri:{}", uri);
        if (uri.contains("/admin/core/login/login") || uri.contains("/admin/core/navigation/menu")) {
            filterChain.doFilter(servletRequest, servletResponse);
            return;
        }

        Map<String, Object> map = new HashMap<>();

        // 检查用户是否登录
        String token = request.getHeader("ADMIN_TOKEN");
        logger.info("token:{}", token);
        if (StringUtils.isEmpty(token)) {
            // 请重新登录
            map.put("code", 10010);
            map.put("message", "请重新登录");
        } else {
            // 通过token查询用户信息
            String str = redisTemplate.opsForValue().get("ADMIN_USER_" + token);
            if (StringUtils.isEmpty(str)) {
                // 请重新登录
                map.put("code", 10010);
                map.put("message", "请重新登录");
            } else {
                filterChain.doFilter(servletRequest, servletResponse);
                return;
            }
        }

        //使用response返回
        response.setStatus(HttpStatus.OK.value()); //设置状态码
        response.setContentType(MediaType.TEXT_PLAIN_VALUE); //设置ContentType
        response.setCharacterEncoding("UTF-8"); //避免乱码
        response.setHeader("Cache-Control", "no-cache, must-revalidate");
        try {
            response.getWriter().write(ObjectMapperUtils.toJsonStr(map));
        } catch (IOException e) {
            logger.error("与客户端通讯异常:"+ e.getMessage(), e);
        }
    }

    @Override
    public void destroy() {
        logger.info("==============销毁过滤器=================");
        Filter.super.destroy();
    }
}
